﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IterationLife.Datas;
using IterationLife.Domains.Sports.Enums;
using IterationLife.Domains.Sports.Services;
using IterationLife.Mobile.AppServices.Dtos;
using IterationLife.Mobile.AppServices.Dtos.Football;
using IterationLife.System.ExternalIdentity;
using IterationLife.System.Repositories;
using IterationLife.System.Services;
using Util;
using Util.Domains.Contexts;

namespace IterationLife.Mobile.AppServices.Services.Football.Implements
{
    public class FootballDeviceService : IFootballDeviceService
    {
        private readonly IApplicationUnitOfWork _unitOfWork;
        private readonly ILoginManager _loginManager;
        private readonly IUserManager _userManager;
        private readonly IExternalUserBindingRepository _externalUserBindingRepository;

        private static List<string> SupportDeviceType = new List<string>
        {
            ExternalUserProviderConstants.MTSports,
            ExternalUserProviderConstants.Zeep,
        };

        public FootballDeviceService(IApplicationUnitOfWork unitOfWork, 
            ILoginManager loginManager,
            IUserManager userManager,
            IExternalUserBindingRepository externalUserBindingRepository)
        {
            _unitOfWork = unitOfWork;
            _loginManager = loginManager;
            _userManager = userManager;
            _externalUserBindingRepository = externalUserBindingRepository;
        }

        public BindedDeviceOutput BindingMTSportsAccount(string account, string password)
        {
            var sportUser=_loginManager.Login(account, password, EquipmentType.MT);
            var externalUserId = sportUser.PartnerUserId;
            _userManager.AddExternalUser(ApplicationContext.User.UserId.ToGuid(), externalUserId,
                ExternalUserProviderConstants.MTSports);
            _unitOfWork.Commit();
            return new BindedDeviceOutput
            {
                DeviceUserId = externalUserId,
                DeviceType = ExternalUserProviderConstants.MTSports
            };
        }

        public List<BindedDeviceOutput> GetUserBindedDevices(Guid userId)
        {
            var bindedDevice= _externalUserBindingRepository.Find()
                .Where(d => d.UserId == userId && SupportDeviceType.Contains(d.ExternalCode))
                .Select(d=>new BindedDeviceOutput
                {
                    DeviceType = d.ExternalCode,
                    DeviceUserId = d.ExternalUserId,
                }).ToList();
            return bindedDevice;
        }
    }
}
